﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Devices.Sensors;
using System.Windows;
using ODS.Model;


namespace ODS
{
    public class GoogleServiceHandler
    {
        public event Action<List<Place>> OnGetPlace;
        public event Action<string, double, double> OnGetGeocodingLocation;


        /// <summary>
        /// Send request to get location by address
        /// </summary>
        /// <param name="address"></param>
        public void GetPlaceByKeyWord(string name)
        {
            string name_new = SplitKeyWord(name);
            
            GooglePlaceRequest request = new GooglePlaceRequest();
            //request.Radius = Constants.DEFAULT_SETTING_RADIUS;
            
            request.Rankby = RankByEnum.distance;
            
            request.LocationName = name_new;
            
            WebClient client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(GetPlace_DownloadStringCompleted);

            Debug.WriteLine(request);

            client.DownloadStringAsync(new Uri(request.ToString()));
        }

        public string SplitKeyWord(string keyword)
        {
            string newkeyword_1st = "";
            string newkeyword_2nd = "";
            newkeyword_1st = keyword.Replace('-', ' ');
            newkeyword_2nd = newkeyword_1st.Replace('_', ' ');
            return newkeyword_2nd;
        }

         void GetPlace_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {

             try
             {
                 if (e.Error != null)
                 {
                     //if (e.Error.ToString().Contains("System.Exception: Metadata file is invalid or corrupted."))
                     //{

                     //    //return;
                     //}
                     OnGetPlace(null);
                     //MessageBox.Show(e.Error.Message);
                     return;
                 }
                 GooglePlaceRespond response = GooglePlaceRespond.ParseFromJSON(e.Result);
                 List<Place> places = new List<Place>();

                 int count = 0;
                 foreach (var p in response.Places)
                 {
                     Place place = new Place();
                     place.Address = p.Address;
                     place.Lattitude = p.Geometry.Location.Lattitude;
                     place.Longitude = p.Geometry.Location.Longitude;
                     place.Name = p.Name;
                     place.PlaceId = p.Id;

                     places.Add(place);

                     count++;
                     if (count >= 8)
                         break;

                 }

                 //debug
                 PrintPlaceName(places);
                 OnGetPlace(places);
             }
             catch (System.Exception ex)
             {
                 MessageBox.Show(ex.Message);
             }
            

            
        }

         /// <summary>
         /// Send request to get location by address
         /// </summary>
         /// <param name="address"></param>
         public void GetPlaceByLatLng(double lat, double lng)
         {

             GooglePlaceRequest request = new GooglePlaceRequest();
             request.Radius = 1000;
             request.Lattitude = lat;
             request.Longtitude = lng;

             WebClient client = new WebClient();
             client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(GetLocation_DownloadStringCompleted);

             Debug.WriteLine(request);

             String baseUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng={0},{1}&sensor=true" ;
             String url = String.Format(baseUrl,lat, lng);

             client.DownloadStringAsync(new Uri(url));
         }

         void GetLocation_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
         {
             if (e.Error != null)
             {
                 OnGetGeocodingLocation("",0,0);
                 return;
             }
             else
             {
                 GoogleGeocodeLocationResponse response = GoogleGeocodeLocationResponse.ParseFromJSON(e.Result);
                 int countResult = response.Results.Count;
                 if (countResult == 0)
                 {
                     OnGetGeocodingLocation("",0,0);
                     return;
                 }

                 OnGetGeocodingLocation(response.Results[0].FormattedAddress, response.Results[0].Geometry.Location.Latitude, response.Results[0].Geometry.Location.Longtitude);
             }
         }


        void PrintPlaceName(List<Place> places)
        {
            foreach (var p in places)
            {
                Debug.WriteLine("PLACE NAME GOOGLE: " + p.Name);
            }
        }
    }
}
